#!/usr/bin/env python3
"""
LLM Bridge TTS Patch - 为 llm_bridge_voice_control_node 添加TTS功能

此文件包含需要添加到 llm_bridge_voice_control_node.py 的代码片段
"""

# ============================================================================
# 1. 在 _setup_publishers 方法后添加 _setup_subscribers 方法
# ============================================================================

def _setup_subscribers(self):
    """Create ROS2 subscribers for vision responses and other inputs."""
    try:
        # Subscribe to vision response for TTS playback
        self.voice_response_sub = self.create_subscription(
            String,
            '/voice_response',
            self.voice_response_callback,
            self.status_qos
        )
        
        self.get_logger().info('✅ Subscribed to /voice_response for TTS playback')
        
        # Optional: Subscribe to odometry for navigation integration
        if hasattr(self, 'monitor_nav_commands') and self.monitor_nav_commands:
            self.odom_sub = self.create_subscription(
                Odometry,
                '/odom',
                self.odometry_callback,
                self.sensor_qos
            )
            
            # Subscribe to laser scan for collision avoidance
            self.laser_sub = self.create_subscription(
                LaserScan,
                '/scan',
                self.laser_callback,
                self.sensor_qos
            )
        
        self.get_logger().info('Subscribers created successfully')
        
    except Exception as e:
        self.get_logger().error(f'Failed to create subscribers: {e}')
        raise


# ============================================================================
# 2. 添加 voice_response_callback 方法
# ============================================================================

def voice_response_callback(self, msg):
    """
    处理视觉识别结果，发送TTS请求到echokit_server
    
    Args:
        msg: String消息，包含视觉识别结果文本
    """
    response_text = msg.data
    self.get_logger().info(f'📢 Received vision response for TTS: {response_text[:100]}...')
    
    # 检查WebSocket连接状态
    if not self.websocket_client or not self.websocket_client.connected:
        self.get_logger().warn('⚠️  WebSocket not connected, cannot send TTS request')
        return
    
    # 通过WebSocket发送TTS请求
    try:
        # 使用asyncio在WebSocket的事件循环中执行
        if self.websocket_client.loop:
            asyncio.run_coroutine_threadsafe(
                self.send_tts_request(response_text),
                self.websocket_client.loop
            )
        else:
            self.get_logger().error('WebSocket event loop not available')
            
    except Exception as e:
        self.get_logger().error(f'Failed to schedule TTS request: {e}')


# ============================================================================
# 3. 添加 send_tts_request 异步方法
# ============================================================================

async def send_tts_request(self, text: str):
    """
    发送TTS请求到echokit_server
    
    Args:
        text: 要转换为语音的文本
    """
    if not self.websocket_client or not self.websocket_client.websocket:
        self.get_logger().warn('WebSocket not available for TTS request')
        return
    
    try:
        # 构造TTS请求消息
        tts_message = {
            'type': 'tts_request',
            'text': text,
            'timestamp': time.time(),
            'source': 'vision_response'
        }
        
        # 发送JSON消息
        message_json = json.dumps(tts_message)
        await self.websocket_client.websocket.send(message_json)
        
        self.get_logger().info(f'🔊 TTS request sent: {text[:50]}{"..." if len(text) > 50 else ""}')
        
    except ConnectionClosed as e:
        self.get_logger().error(f'WebSocket connection closed while sending TTS: {e}')
        self.websocket_client.connected = False
        
    except Exception as e:
        self.get_logger().error(f'Failed to send TTS request: {e}')


# ============================================================================
# 4. 可选：添加 odometry_callback 和 laser_callback（如果需要导航集成）
# ============================================================================

def odometry_callback(self, msg):
    """处理里程计数据"""
    # 更新机器人位置信息
    pass


def laser_callback(self, msg):
    """处理激光扫描数据，用于碰撞检测"""
    # 检查前方障碍物
    pass


# ============================================================================
# 5. 在 __init__ 方法中调用 _setup_subscribers
# ============================================================================

# 在 __init__ 方法的这一行之后：
#     self._setup_publishers()
# 
# 添加：
#     self._setup_subscribers()


# ============================================================================
# 使用说明
# ============================================================================

"""
将以上代码片段添加到 llm_bridge_voice_control_node.py 的 LLMBridgeVoiceControlNode 类中：

1. 在 _setup_publishers 方法后添加 _setup_subscribers 方法
2. 在类的任意位置添加 voice_response_callback 方法
3. 在类的任意位置添加 send_tts_request 方法
4. 在 __init__ 方法中，在 self._setup_publishers() 之后调用 self._setup_subscribers()

修改后的 __init__ 方法应该是：
    def __init__(self):
        super().__init__('llm_bridge_voice_control_node')
        # ... 其他初始化代码 ...
        self._setup_qos_profiles()
        self._setup_publishers()
        self._setup_subscribers()  # <-- 添加这一行
        self._setup_timers()
        self._setup_websocket_client()
        # ... 其他代码 ...
"""
